package com.rentong.wx.utils;

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;


public class AESUtils {

	public static final String ALGORITHM = "AES/ECB/PKCS7Padding";


	public static String encode(String data,String key) throws Exception{
		Security.addProvider(new BouncyCastleProvider());
		String md5Key = DigestUtils.md5Hex(key).toLowerCase();
		SecretKeySpec keySpec = new SecretKeySpec(md5Key.getBytes(), "AES");
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, keySpec);
		byte[] encode = Base64.encodeBase64(cipher.doFinal(data.getBytes()));
		return new String(encode,"UTF-8");
	}


    public static String decode(String data,String key) throws Exception{
       byte[] decodeBase64 = Base64.decodeBase64(data);
       String md5Key = DigestUtils.md5Hex(key).toLowerCase();
       Security.addProvider(new BouncyCastleProvider());
       Cipher cipher = Cipher.getInstance(ALGORITHM);
       SecretKey keySpec = new SecretKeySpec(md5Key.getBytes(), "AES"); //生成加密解密需要的Key
       cipher.init(Cipher.DECRYPT_MODE, keySpec);
       byte[] decoded = cipher.doFinal(decodeBase64);
       return new String(decoded, "UTF-8");
    }

}
